package com.hlx.herostory.cmdhandler;

import com.hlx.herostory.Broadcaster;
import com.hlx.herostory.model.User;
import com.hlx.herostory.model.UserManager;
import com.hlx.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd msg) {
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if (null == userId) {
            return;
        }

        User existUser = UserManager.getByUserId(userId);
        if(existUser == null) {
            return;
        }

        long nowTime = System.currentTimeMillis();

        existUser.moveState.fromPosX = msg.getMoveFromPosX();
        existUser.moveState.fromPosY = msg.getMoveFromPosY();
        existUser.moveState.toPosX = msg.getMoveToPosX();
        existUser.moveState.toPosY = msg.getMoveToPosY();
        existUser.moveState.startTime = nowTime;

        GameMsgProtocol.UserMoveToResult.Builder resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveToPosX(msg.getMoveToPosX());
        resultBuilder.setMoveToPosY(msg.getMoveToPosY());
        resultBuilder.setMoveFromPosX(msg.getMoveFromPosX());
        resultBuilder.setMoveFromPosY(msg.getMoveFromPosY());
        resultBuilder.setMoveStartTime(nowTime);

        GameMsgProtocol.UserMoveToResult newResult = resultBuilder.build();
        Broadcaster.broadcast(newResult);
    }
}
